<template>
  <div id="tableConfig">
    <div class="columnsInfo">
      <h4>配置信息</h4>
      <el-form :model="excelImportDefineObject" :rules="rules" ref="ruleForm" :inline="true" label-width="100px" class="demo-ruleForm" >
        <!-- 【模板编号】 -->
        <el-form-item :label="$t('transmit.templateNo')" prop="templateNo" class="base-width-50">
          <el-input type="text" autosize v-model="excelImportDefineObject.templateNo"></el-input>
        </el-form-item>
        <!-- 【模板名称】 -->
        <el-form-item :label="$t('transmit.templateName')" prop="templateName" class="base-width-50">
          <el-input type="text" autosize v-model="excelImportDefineObject.templateName"></el-input>
        </el-form-item>
        <!-- 【导入类型】 -->
        <el-form-item :label="$t('app.importType')" prop="importType" class="base-width-50">
          <el-select v-model="excelImportDefineObject.importType" :disabled="!newFlag" placeholder="" @change="findImportTypeField($event)">
            <el-option v-for="item in excelImportTypes" :key="item.code" :label="item.description" :value="item.code" />
          </el-select>
        </el-form-item>
        <!-- 【sheet类型】 -->
        <el-form-item :label="$t('app.sheetType')" prop="templateSheetType" class="base-width-50">
          <el-select v-model="excelImportDefineObject.templateSheetType" :disabled="!newFlag" placeholder="" @change="renderTabs($event)">
            <el-option :label="$t('code.sheetType1')" :value="1"/>
            <el-option :label="$t('code.sheetType2')" :value="2"/>
            <el-option :label="$t('code.sheetType3')" :value="3"/>
          </el-select>
        </el-form-item>
        <br>
        <el-form-item label="" prop="readLineNum">
          <span class="templateName">Excel导入文件，从第<el-input style="width: 10%; margin: 0px 10px;" type="number" v-model="excelImportDefineObject.readLineNum" />行开始读取业务数据</span>
        </el-form-item>
        <br>
        <el-form-item :label="$t('app.remark')" prop="remark" class="base-width-50">
          <el-input type="textarea" autosize v-model="excelImportDefineObject.remark"></el-input>
        </el-form-item>
        <br>
        <div style="margin-top: 10px;">
          <el-form-item label="" prop="isEnabled" class="base-width-50">
            <span>{{$t('transmit.isEnabled')}}<el-switch style="margin-left: 10px;" v-model="excelImportDefineObject.isEnabled" active-color="#13ce66" /></span>
          </el-form-item>
          <el-form-item label="" prop="isDefault" class="base-width-50">
            <span>{{$t('transmit.isDefault')}}<el-switch style="margin-left: 10px;" v-model="excelImportDefineObject.isDefault" active-color="#13ce66" /></span>
          </el-form-item>
        </div>

        <!-- tabs-标签页 -->
        <br>
        <el-form-item class="base-width-100">
          <el-tabs type="border-card" @tab-click="tabIndex($event)">
            <el-tab-pane v-for="(item, index) in tabsList" :key="item.index" :label="item.name">
              <el-table :class="`table_${index}`" :data="item.tableData" border style="width: 100%" row-key="id">
                <el-table-column align="center" label="序列" prop="id">
                  <template slot-scope="scope">
                    <span class="txt">{{ scope.row.id }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" :label="$t('transmit.fieldCode')" prop="fieldCode">
                  <template slot-scope="scope">
                    <span class="txt">{{ scope.row.fieldCode }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" :label="$t('transmit.fieldName')" prop="fieldName">
                  <template slot-scope="scope">
                    <span class="txt">{{ scope.row.fieldName }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" :label="$t('transmit.fieldDesc')" prop="fieldDesc">
                  <template slot-scope="scope">
                    <span class="txt">{{ scope.row.fieldDesc }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" :label="$t('transmit.isMustInput')" prop="isMustInput">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.isMustInput" placeholder="">
                      <el-option :label="$t('code.yes')" :value="1"/>
                      <el-option :label="$t('code.no')" :value="0"/>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column align="center" :label="$t('transmit.excelNum')" prop="excelNum" >
                  <template slot-scope="scope">
                    <el-input type="text" class="item" onkeyup="this.value=this.value.replace(/[^A-Z]/g,'')" v-model="scope.row.excelNum" placeholder=""></el-input>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-form-item>

        <!-- 保存|取消 -->
        <div class="btn_b">
          <el-button type="primary" :disabled="!this.btnPermNameList.includes('EN02070204')&&!this.btnPermNameList.includes('WM03160204')" @click="saveObj('ruleForm')">{{$t("common.save")}}</el-button>
          <el-button :disabled="!this.btnPermNameList.includes('EN02070205')&&!this.btnPermNameList.includes('WM03160205')" @click="cancel">{{$t("common.cancel")}}</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import Sortable from 'sortablejs';
import baseMixin from "@/mixins/BaseMixin";
import {
  queryExcelImportDefineById,
  insertExcelImportDefine,
  updateExcelImportDefine,
  getExcelImportType,
  findImportTypeField
} from "@/api/transmit/transmit";

export default {
  name: "excelImportDefineDrawer",
  mixins: [baseMixin],
  data() {
    return {
      ///////////////////
      tabsList: [{
          index: 1,
          name: "Sheet" + 1,
          tableData: []
      }],
      // 确定操作哪个sheet
      tabsIndex: 0,
      // 拖拽类
      dragClass:[],
      ///////////////////
      dropCol: [
        {label: this.$t('config.serial'), prop: 'id'},
        {label: this.$t('transmit.fieldCode'), prop: 'fieldCode'},
        {label: this.$t('transmit.fieldName'), prop: 'fieldName'},
        {label: this.$t('transmit.fieldDesc'), prop: 'fieldDesc'},
        {label: this.$t('transmit.isMustInput'), prop: 'isMustInput'},
        {label: this.$t('transmit.excelNum'), prop: 'excelNum'}
      ],
      // 主表
      excelImportDefineObject: {
        // 模板编号
        templateNo: undefined,
        // 模板名称
        templateName: undefined,
        // 文件读取行数
        readLineNum: undefined,
        // 导入类型
        importType: undefined,
        // 模板sheet类型
        templateSheetType: undefined,
        // 备注
        remark: undefined,
        // 是否生效
        isEnabled: false,
        // 是否默认模板
        isDefault: false,
        sheetOne: undefined,
        sheetTwo: undefined,
        // 子表
        excelImportDefineDtls: undefined
      },
      newFlag: false,
      copyFlag: false,
      rules: {
        templateNo: [{required: true, message: this.$inputPlease("transmit.templateNo"), trigger: 'change'}],
        templateName: [{required: true, message: this.$inputPlease("transmit.templateName"), trigger: 'change'}],
        importType: [{required: true, message: this.$inputPlease("app.importType"), trigger: 'change'}],
        readLineNum: [{required: true, message: this.$inputPlease("app.readLine"), trigger: 'change'}],
        templateSheetType: [{required: true, message: '请选择sheet类型', trigger: 'change'}]
      },
      excelImportTypes: [],
      // 当前tabs下标
      currentTabsIndex: 0
    }
  },
  methods: {
    // tabIndex
    tabIndex(tab, event) {
      console.log("tab = %o, event = %o", tab, event);
      this.tabsIndex = tab.index;
    },
    // 查找导入类型字段
    findImportTypeField(e) {
      const _this = this;
      findImportTypeField(e).then(res => {
        console.log("查找导入类型字段 = %o， 该类型对应的字段配置 = %o", e, res);

          let data = res.data;
          if (data !== null && data.length > 0) {
/*
            let index_0 = _this.tabsList[_this.tabsIndex].tableData.length !== 0;
            data.forEach((item, index) => {

              if (index_0) {
                item.id = _this.tabsList[_this.tabsIndex].tableData[_this.tabsList[_this.tabsIndex].tableData.length - 1].id + 1;
              } else {
                item.id = index + 1;
              }
              item.sheetNumber = _this.tabsIndex;
              _this.tabsList[_this.tabsIndex].tableData.push(item);
            });

            // 渲染回调
            this.$nextTick(() => {
              // 不同
              if (this.tabsList.length > this.dragClass.length) {
                // 初始化拖拽行
                this.rowDrop();
              }
            });*/
            data.forEach((item, index) => {
              // 设置序列号
              item.id = index + 1;
              // 区别工作区
              item.sheetNumber = _this.tabsIndex;
            });
            // 选择类型重置参数
            _this.tabsList[_this.tabsIndex].tableData = data;
          } else {

            let text = "该类型没有对应的字段配置";
            _this.$message.warning(text);
          }

          // 没有记录则初始化
          if (_this.dragClass.length === 0) {
            // 初始化拖拽行
            this.rowDrop();
          }
      });

    },
    // 渲染标签
    renderTabs(e) {

      let tabsNo = this.tabsList.length;
      if (e !== tabsNo) {
        while (this.tabsList.length - e !== 0) {
          let no = this.tabsList.length;
          if (e > no) {
            no = no + 1;
            this.tabsList.push({
              index: no,
              name: "Sheet" + no,
              tableData: []
            });
          } else {
            if (tabsNo !== 1) {
              no = no - 1;
              this.tabsList.splice(no, 1);
            }
          }
        }
      }
    },
    getExcelImportType() {
      getExcelImportType().then(res => {
        this.excelImportTypes = res.list;

        // 获取导导入类型 再获取列表渲染验证
        this.newFlag = this.$store.state.newFlag;
        let query = this.$route.query;

        if (!this.newFlag) {
          this.selectData = this.$store.state.routeData;
          this.getData();
        }

        this.copyFlag = query.copy;
        if (this.copyFlag) {
          this.selectData = query.obj;
          this.getData();
        }
      });
    },
    toSaveRequest() {

      insertExcelImportDefine(this.excelImportDefineObject).then(res => {
          this.$message.success(this.$t('app.saveMes'));
          this.cancel();
        
      });
    },
    toEditRequest() {

      updateExcelImportDefine(this.excelImportDefineObject).then(res => {
          this.$message.success(this.$t('app.upMes'));
          this.cancel();
        
      });
    },
    logic() {

      // 转义-是否生效
      if (this.excelImportDefineObject.isEnabled) {
        this.excelImportDefineObject.isEnabled = 1;
      } else {
        this.excelImportDefineObject.isEnabled = 0;
      }

      // 转义-是否默认模板
      if (this.excelImportDefineObject.isDefault) {
        this.excelImportDefineObject.isDefault = 1;
      } else {
        this.excelImportDefineObject.isDefault = 0;
      }

      // 转义-导入类型
      let importType = this.excelImportDefineObject.importType;
      this.excelImportTypes.forEach((item) => {
        if (importType === item.description) {
          this.excelImportDefineObject.importType = item.code;
        }
      });

      // 初始化子表对象
      this.excelImportDefineObject.excelImportDefineDtls = [];

      // 取出tabs的值
/*      this.tabsList.forEach((item) => {
        item.tableData.forEach((K) => {
          this.excelImportDefineObject.excelImportDefineDtls.push(K);
        });
      });*/
      this.tabsList.forEach((item) => {
        item.tableData.forEach((x) => {
          this.excelImportDefineObject.excelImportDefineDtls.push(x);
        });
      });

      // 保存 | 更新数据
      if (this.newFlag) {
        // 新增逻辑
        this.toSaveRequest();
      } else {
        // 编辑逻辑
        this.toEditRequest();
      }
    },
    saveObj(ruleForm) {
      // 验证参数
      this.$refs[ruleForm].validate((valid) => {
        // 验证成功
        if (valid) {
          return this.logic();
        }
        // 验证失败
        else {
          let text = "参数不能为空";
          return this.$message.warning(text);
        }
      });
    },
    cancel() {
      this.$router.push({name: "excelImportDefine"})
    },
    getData() {
      queryExcelImportDefineById(this.selectData.id).then(res => {
          this.excelImportDefineObject = res.data;

          // 转义-导入类型
          let importType = this.excelImportDefineObject.importType;
          this.excelImportTypes.forEach((item) => {
            if (importType == item.code) {
              this.excelImportDefineObject.importType = item.description;
            }
          });
          // 转义-是默认值
          let isDefault = this.excelImportDefineObject.isDefault;
          if (isDefault === 1) {
            this.excelImportDefineObject.isDefault = true;
          } else {
            this.excelImportDefineObject.isDefault = false;
          }

          // 转义-已启用
          let isEnabled = this.excelImportDefineObject.isEnabled;
          if (isEnabled) {
            this.excelImportDefineObject.isEnabled = true;
          } else {
            this.excelImportDefineObject.isEnabled = false;
          }

          // 渲染tabs
          let templateSheetType = this.excelImportDefineObject.templateSheetType;
          this.renderTabs(templateSheetType);

          // 初始化sheet1
          this.excelImportDefineObject.excelImportDefineDtls.forEach((item) => {
            this.tabsList[item.sheetNumber].tableData.push(item);
          });

          // 复制清理主表id
          if (this.copyFlag) {
            this.excelImportDefineObject.id = undefined;
          }

          // 渲染回调
          this.$nextTick(() => {
            // 不同
            if (this.tabsList.length > this.dragClass.length) {
              // 初始化拖拽行
              this.rowDrop();
            }
          });
        
      });
    },
    // 行拖拽
    rowDrop() {

      const _this = this;
      console.log("初始化 行拖拽");
      let index = _this.dragClass.length;
      if (index < 3) {

        // 此时找到的元素是要拖拽元素的父容器 order-table
        let draggable = ".el-table__row";
        let selectors = " .el-table__body-wrapper tbody";

        let classS = ".table_" + index;
        let str = classS + selectors;
        const tbody = document.querySelector(str);

        Sortable.create(tbody, {
          // 指定父元素下可被拖拽的子元素
          draggable: draggable,
          onEnd({newIndex, oldIndex}) {
            const currRow = _this.tabsList[index].tableData.splice(oldIndex, 1)[0];
            _this.tabsList[index].tableData.splice(newIndex, 0, currRow);
          }
        });

        // 添加内容验证
        _this.dragClass.push(classS);

        // 验证是否从sheet1 -> sheet3
        if (_this.dragClass.length < _this.excelImportDefineObject.templateSheetType) {
          console.log("再次调用");
          this.rowDrop();
        }
      }
    }
  },
  watch: {
  },
  mounted() {

    this.getExcelImportType();
  }
}
</script>

<style lang="scss" scoped>

.demo-ruleForm {
  .el-select {
    height: 25px;

    ::v-deep .el-input {
      height: 25px;
    }
  }
}

.templateName {
  width: 100%;
  font-size: initial;
  margin-left: 8px;
}

.btn_b {
  width: 100%;
  text-align: center;
  margin-top: 16px;
}
</style>